//
//  OAuthViewController.swift
//  0730Microblog
//
//  Created by ding on 15/7/31.
//  Copyright © 2015年 ding. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let urlRequest = NSURLRequest(URL: DINGNetTool.sharedNetTool.getOAuthAddress())
        webView.loadRequest(urlRequest)
        webView.delegate = self
        
    }
    private let webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.whiteColor()
        navigationItem.title = "授权登陆"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeOAuthVC")
        
    }
    
    func closeOAuthVC() {
        dismissViewControllerAnimated(true) { () -> Void in
            print("xiaohuixiaohuixiaohui")
        }
    }
    /// MARK: - WebView的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        
        if !urlString!.hasPrefix(DINGNetTool.sharedNetTool.redirectUri) {
            return true
        }
        
        if let urlQuery = request.URL?.query where urlQuery.hasPrefix("code=") {
            // 拿到授权码
            let authorizeCode = urlQuery.substringFromIndex(advance(urlQuery.startIndex, "code=".characters.count))
            print(authorizeCode)
            // 根据授权码拿到“通行证”Token
            getAccessToken(authorizeCode)
        
        } else {
            closeOAuthVC()
        }
        
        return false
    }
    
    // MARK: - 根据授权码拿到“通行证”Token
    private func getAccessToken(authorizeCode: String) {
        DINGNetTool.sharedNetTool.loadAccessToken(authorizeCode) { (result, error) -> () in
            if error != nil || result == nil {
               self.netError()
                return
            }
            let userA = UserAcountInfo(dict: result!)
            userA.saveUserAccountInfo()
            userA.loadMicroBlogUserInfo({ (loadMicroBlogUserInfoError) -> () in
//                print(result)
                if loadMicroBlogUserInfoError != nil {
                    self.netError()
                    print(loadMicroBlogUserInfoError)
                    return
                }
                print("loadMicroBlogUserInfo---Success")
                
                NSNotificationCenter.defaultCenter().postNotificationName(DINGSwitchRootViewControllerNotification, object: false)
                
                self.closeOAuthVC()
                
            })
        }
        
    }
    
    private func netError() {
        SVProgressHUD.showInfoWithStatus("网络不给力啊")
        
        // 延时一段时间再关闭
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) {
            self.closeOAuthVC()
        }
    }

}
